package com.yqy.wordvideodemo.permission;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;

import com.yqy.wordvideodemo.permission.bean.AppPermission;
import com.yqy.wordvideodemo.permission.callback.IPermissionsCallback;
import com.yqy.wordvideodemo.permission.utils.PerCommonUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @CreateTime: 2019/7/31
 * @Author: Desol
 * @AssociatedPage:
 * @Description:
 */
public class XPermission {
    private static XPermission instance;
    private Activity activity;

    public static final int REQUEST_PERMISSION_CODE = 1001;//默认请求code
    protected int requestCode = 0;//跳转系统权限设置页面的请求回调code

    private String[] req;//请求权限
    private IXPermissionCallback cPermissionCallback;//权限请求回调接口

    private int deniedNumberMax = 0;//拒绝次数最大值
    private int deniedNumber;//拒绝次数

    private AlertDialog showAppDetDialog = null;//对话框

    public static XPermission getInstance() {
        if (instance == null) {
            instance = new XPermission();
        }
        return instance;
    }

    @Deprecated
    public void init(Activity activity) {
        showAppDetDialog = null;
        cPermissionCallback = null;
        requestCode = 0;
        deniedNumberMax = 0;
        this.activity = activity;
        PermissionHelper.getInstance().init(activity);
    }

    public XPermission with(Activity activity) {
        showAppDetDialog = null;
        cPermissionCallback = null;
        requestCode = 0;
        deniedNumberMax = 0;
        this.activity = activity;
        PermissionHelper.getInstance().with(activity);
        return this;
    }

    public void onCancel() {
        this.activity = null;
        PermissionHelper.getInstance().onCancel();
    }

    public XPermission setDeniedNumberMax(int deniedNumberMax) {
        this.deniedNumberMax = deniedNumberMax;
        return this;
    }

    public void checkPermission(String[] perms, @NonNull IXPermissionCallback cPermissionCallback) {
        checkPermission(perms, cPermissionCallback, 0);
    }

    public void checkPermission(String[] perms, @NonNull IXPermissionCallback cPermissionCallback, int requestCode) {
        this.cPermissionCallback = cPermissionCallback;
        this.requestCode = requestCode == 0 ? REQUEST_PERMISSION_CODE : requestCode;

        req = PermissionHelper.getInstance().checkPermissions(perms);

        if (req.length == 0) {
            if (cPermissionCallback != null)
                cPermissionCallback.onAcceptedAll();
        } else {
            deniedNumber = 0;
            requestPermissions(req, cPermissionCallback);
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == this.requestCode) {
            String[] cc = PermissionHelper.getInstance().checkPermissions(req);

            if (cPermissionCallback != null && cPermissionCallback.onActivityResult(cc, requestCode, resultCode, data)) {
                return;
            }

            if (cc.length == 0) {
                if (cPermissionCallback != null)
                    cPermissionCallback.onAcceptedAll();
            }
        }
    }

    private void requestPermissions(String[] perms, @NonNull IXPermissionCallback cPermissionCallback) {
        PermissionHelper.getInstance().requestPermissions(perms, new IPermissionsCallback() {

            @Override
            public void onAcceptedAll() {
                if (cPermissionCallback != null)
                    cPermissionCallback.onAcceptedAll();
            }

            @Override
            public void onAccepted(List<AppPermission> permissions) {
                /** cPermissionCallback.onAccepted() return true 就走用户自定义的onAccepted()逻辑 **/
                if (cPermissionCallback != null && cPermissionCallback.onAccepted(permissions)) {
                    return;
                }
            }

            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onDeniedAndReject(List<AppPermission> permissionsDenied, List<AppPermission> permissionsReject) {
                /** cPermissionCallback.onDeniedAndReject() return true 就走用户自定义的onDeniedAndReject()逻辑 **/
                if (cPermissionCallback != null && cPermissionCallback.onDeniedAndReject(permissionsDenied, permissionsReject)) {
                    return;
                }


                /** 申请的权限全部选择不再询问,跳转到该APP系统权限设置界面 **/
                if (permissionsDenied.size() == permissionsReject.size()) {
                    showAppDetails(PermissionHelper.getInstance().getShowDialogMessage(permissionsReject));
                }
            }

            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onDenied(List<AppPermission> permissions) {
                /** cPermissionCallback.onDenied() return true 就走用户自定义的onDenied()逻辑 **/
                if (cPermissionCallback != null && cPermissionCallback.onDenied(permissions)) {
                    return;
                }
                /** 拒绝次数 **/
                deniedNumber++;
                /** 拒绝次数到最大值显示对话框 **/
                if (deniedNumberMax != 0 && deniedNumber == deniedNumberMax) {
                    showAppDetails(PermissionHelper.getInstance().getShowDialogMessage(permissions));
                    return;
                }


                /** 用户点击拒绝后,再次询问,未勾选不在询问的权限 **/
                List<AppPermission> ls = new ArrayList<>();
                for (AppPermission appPermission : permissions) {
                    if (appPermission.shouldShowRequestPermissionRationable) {
                        ls.add(appPermission);
                    }
                }
                if (ls.size() > 0) {
                    requestPermissions(PerCommonUtil.toArray(permissions), cPermissionCallback);
                }
            }
        });
    }


    /**
     * 打开 APP 的详情设置 如果需要自定义dialog样式 继承XPermission重写该方法
     */
    protected void showAppDetails(String message) {
        if (activity == null)
            return;

        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setMessage(message);
        builder.setPositiveButton("手动授权", (dialog, which) ->
        {
            dialog.dismiss();
            PermissionHelper.getInstance().gotoPermissionDetail(requestCode == 0 ? REQUEST_PERMISSION_CODE : requestCode);
        });

        builder.setCancelable(false);
        builder.setNegativeButton("取消", (dialog, which) ->
                dialog.dismiss()
        );

        if (null == showAppDetDialog)
            showAppDetDialog = builder.create();
        if (null != showAppDetDialog && !showAppDetDialog.isShowing()) {
            showAppDetDialog.setMessage(message);
            showAppDetDialog.show();
        }
    }


}
